/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package client.pipeConnector;

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;

/**
 *
 * @author Александр Емельянов (mr.lex91@gmail.com)
 */
public class PipeConnectorStreamed implements IPipe{
    private PipedOutputStream writer;
    private PipedInputStream reader;
    private String part="";

    public static IPipe[] createPipe() throws IOException
    {
        IPipe[] pc=new PipeConnectorStreamed[2];
        PipedOutputStream pw1=new PipedOutputStream();
        PipedInputStream pr1=new PipedInputStream(pw1);
        PipedOutputStream pw2=new PipedOutputStream();
        PipedInputStream pr2=new PipedInputStream(pw2);
        pc[0]=new PipeConnectorStreamed(pr1,pw2);
        pc[1]=new PipeConnectorStreamed(pr2,pw1);
        return pc;
    }
    PipeConnectorStreamed(PipedInputStream reader, PipedOutputStream writer)
    {
        this.reader=reader;
        this.writer=writer;
    }

    public String Read()
    {
        int n=1024;
        int i=n;
        byte[] buf1 = new byte[n];
        String str=part;
        try {
            while (true)
            {
                if (str.contains("<END>"))
                {
                    if (str.indexOf("<END>")+6<str.length()) part=str.substring(str.indexOf("<END>")+5, str.length());
                    else part="";
                    str=str.substring(0, str.indexOf("<END>"));
                    return str;
                }
                if(i<n) return str;
                i = reader.read(buf1);
                str+=new String(buf1,0,i);
            }
        } catch (IOException ex) {}
        return str;
    }
    public void Write(String text)
    {
        ByteBuffer buf = ByteBuffer.allocate(2*text.length()+5);
        buf.clear();
        buf.put((text+"<END>").getBytes());
        buf.flip();
	try {
	    writer.write(buf.array(),0,text.length()+5);
	} catch (IOException ex) {}
    }
}
